package sys.utils;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Encrypter {
    
    private static final String METODO_ENCRIPTACAO = "AES";
    public static final byte[] CHAVE = {75, 4, 4, -23, 68, 88, 46, 37, 45, 48, 10, -1, -37, -45, 70, -16};
   
 

    public static String encrypt(String value) throws EncryptorException {
        try {
            
            SecretKeySpec skeySpec = new SecretKeySpec(CHAVE, METODO_ENCRIPTACAO);

            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(1, skeySpec);
            byte[] encrypted = cipher.doFinal(value.getBytes());
            return new BASE64Encoder().encode(encrypted);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                IllegalBlockSizeException | BadPaddingException e) {
            throw new EncryptorException("Erro ao criptografar: " + e.getMessage());
        }
    }
    public static String decrypt(String encrypted) throws EncryptorException {
        byte[] decrypted = null;
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(CHAVE, METODO_ENCRIPTACAO);
            
            byte[] decoded = new BASE64Decoder().decodeBuffer(encrypted);
            
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, skeySpec);
            decrypted = cipher.doFinal(decoded);
        } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException |
                InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            Mensagens.msgErro("nao foi possível descriptografar");
            throw new EncryptorException("Erro ao decriptografar: " + e.getMessage());
        }
        return new String(decrypted);
    }
}
